package me.lensfrex.doubandps.data;

import me.lensfrex.doubandps.excel.ExcelWorker;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.logging.Logger;

public class MovieInformationDataExporter {
    private static final Logger log = Logger.getLogger("DataExporterLogger");

    ExcelWorker<MovieInformation> excelWorker = null;
    private final Class<MovieInformation> dataClass;

    public MovieInformationDataExporter(String excelFilePath, Class<MovieInformation> dataClass) {
        this.dataClass = dataClass;
        this.createNewExcelWorker(excelFilePath);
    }

    public boolean createNewExcelWorker(String newExcelFilePath) {
        try {
            excelWorker = new ExcelWorker<>(newExcelFilePath, dataClass);
        } catch (IOException e) {
            excelWorker = null;
            log.severe("创建ExcelWorker时出现I/O问题。ErrMessage：" + e.getMessage() +
                    "指定的Excel文件路径：" + newExcelFilePath);

            return false;
        } catch (Exception e) {
            excelWorker = null;
            log.severe("创建ExcelWorker时发生未知错误.ErrMessage：" + e.getMessage() +
                    "指定的Excel文件路径：" + newExcelFilePath);

            return false;
        }

        return true;
    }

    public void insertDataIntoExcel(int sheetIndex, Collection<MovieInformation> source) {
        excelWorker.addAllDataToSheet(sheetIndex, source);
    }

    public void exportInformationByYear(List<MovieInformation> source) {
        excelWorker.createNewSheet("2000年前");
        int sheetAmount = excelWorker.createNewSheet("2000年后");

        ArrayList<MovieInformation> movieBefore2000 = new ArrayList<>();
        ArrayList<MovieInformation> movieAfter2000 = new ArrayList<>();
        for (MovieInformation movieInformation : source) {
            if (movieInformation.getYear() < 2000) {
                movieBefore2000.add(movieInformation);
            } else {
                movieAfter2000.add(movieInformation);
            }
        }

        excelWorker.addAllDataToSheet(sheetAmount - 2, movieBefore2000);
        excelWorker.addAllDataToSheet(sheetAmount - 1, movieAfter2000);

        excelWorker.finish();
        log.info("已完成导出。");
    }
}
